package com.yfqy.admin.resource;

import cn.hutool.json.JSONUtil;
import com.github.pagehelper.PageInfo;
import com.yfqy.admin.domain.dto.revenue.AddRevenueRecord;
import com.yfqy.admin.domain.dto.revenue.DailyIncomeDTO;
import com.yfqy.admin.domain.dto.revenue.ModifyRevenueRecord;
import com.yfqy.admin.domain.dto.revenue.PaymentTypeStatsDTO;
import com.yfqy.admin.domain.dto.revenue.RevenueRecordDTO;
import com.yfqy.admin.domain.dto.revenue.RevenueRecordQuery;
import com.yfqy.admin.domain.dto.revenue.RevenueStatisticsDTO;
import com.yfqy.admin.domain.entity.RevenueRecord;
import com.yfqy.admin.service.RevenueRecordService;
import com.yfqy.admin.util.ExcelUtils;
import com.yfqy.admin.domain.vo.common.ResultVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

/**
 * 收入记录-手工录账
 */
@RestController
@RequestMapping("/api/internal/revenueRecord")
public class RevenueRecordController {

    private static final Logger LOGGER = LoggerFactory.getLogger(RevenueRecordController.class);

    private final RevenueRecordService revenueRecordService;

    public RevenueRecordController(RevenueRecordService revenueRecordService) {
        this.revenueRecordService = revenueRecordService;
    }

    /**
     * 解析每日营业收入数据
     *
     * @return
     */

    @PostMapping("/insertRevenueRecords")
    public ResultVO<String> insertRevenueRecords(@RequestParam("file") MultipartFile file) {
        try {
            List<RevenueRecord> dataList = ExcelUtils.parseExcel(file);
            // 处理解析后的数据（如存入数据库）
            LOGGER.info(JSONUtil.toJsonStr(dataList));
            revenueRecordService.insertRevenueRecords(dataList);
            return ResultVO.success("解析成功，共处理 " + dataList.size() + " 条数据");
        } catch (Exception e) {
            return ResultVO.fail("解析失败: " + e.getMessage());
        }
    }

    /**
     * 交易手工账列表
     *
     * @param query
     * @return
     */
    @PostMapping("/pageList")
    public ResultVO<PageInfo<RevenueRecordDTO>> pageList(@RequestBody RevenueRecordQuery query) {
        return revenueRecordService.pageList(query);
    }

    /**
     * 交易手工账列表
     *
     * @param addRevenueRecord
     * @return
     */
    @PostMapping("/addRevenueRecord")
    public ResultVO<String> addRevenueRecord(@RequestBody @Validated AddRevenueRecord addRevenueRecord) {
        return revenueRecordService.addRevenueRecord(addRevenueRecord);
    }

    /**
     * 交易手工账列表
     *
     * @param modifyRevenueRecord
     * @return
     */
    @PostMapping("/modifyRevenueRecord")
    public ResultVO<String> modifyRevenueRecord(@RequestBody @Validated ModifyRevenueRecord modifyRevenueRecord) {
        return revenueRecordService.modifyRevenueRecord(modifyRevenueRecord);
    }

    /**
     * 每日营业统计（日、周、月、年）
     *
     * @return
     */
    @GetMapping("/revenueStatistics")
    public ResultVO<RevenueStatisticsDTO> revenueStatistics() {
        return revenueRecordService.revenueStatistics();
    }

    /**
     * n天前到今天的日收入走势
     *
     * @param days
     * @return
     */
    @GetMapping("/last-n-days")
    public ResultVO<List<DailyIncomeDTO>> getLastNDaysIncome(@RequestParam(value = "days", defaultValue = "7") int days) {
        if (days <= 0) {
            throw new IllegalArgumentException("天数必须大于0");
        }
        return ResultVO.data(revenueRecordService.getLastNDaysIncome(days));
    }

    @GetMapping("/payment-type/last-30days")
    public ResultVO<List<PaymentTypeStatsDTO>> getLast30DaysStats() {
        return ResultVO.data(revenueRecordService.getLast30DaysPaymentStats());
    }

    @GetMapping("/payment-type/date-range")
    public ResultVO<List<PaymentTypeStatsDTO>> getStatsByDateRange(
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {
        return ResultVO.data(revenueRecordService.getPaymentStatsByDateRange(
                Date.from(startDate.atStartOfDay(ZoneId.systemDefault()).toInstant()),
                Date.from(endDate.atStartOfDay(ZoneId.systemDefault()).toInstant())
        ));
    }

}
